<template>
  <div>
    <template v-if="isLoading">
      <!-- 显示正在加载的提示或占位符 -->
      <div>Loading...</div>
    </template>

    <template v-else>
      <div style="height: 100vh; overflow-x: hidden">
        <el-row :gutter="20" justify="space-between">
          <el-col :span="8">
            <weatherDay :qweather="qweather" :on-geticon="geticon"></weatherDay>
          </el-col>

          <el-col :span="16">
            <weatherData :qweather="qweather"></weatherData>
          </el-col>
        </el-row>

        <el-row :gutter="20" justify="space-between" class="mt-4">
          <el-col :span="16">
            <weatherIndicators :zs="zs"></weatherIndicators>
          </el-col>
          <el-col :span="8">
            <futureWeather :qweather="qweather" :on-geticon="geticon"></futureWeather>
          </el-col>
        </el-row>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeUnmount, provide } from 'vue';
import SunCalc from 'suncalc';
import { useweatherStore } from '@/stores/weatherStores.js';
import { useUserStore } from '@/stores/userinfo';
import weatherDay from './weatherComponents/WeatherDay.vue';
import weatherData from './weatherComponents/WeatherData.vue';
import futureWeather from './weatherComponents/FutureWeather.vue';
import weatherIndicators from './weatherComponents/WeatherIndicators.vue';

const weatherStore = useweatherStore();

const { proxy } = getCurrentInstance();
const userStore = ref(useUserStore());

let qweather = reactive({});
let zs = reactive({});
const isLoading = ref(true);
async function loadData() {
  const result = await proxy.$ax.get(
    `/5001/api/Rss/GetWeather?cityName=${userStore.value.locationData.address_component.city.replace('市', '')}`,
  );
  const today = new Date();
  const { sunrise, sunset } = SunCalc.getTimes(
    today,
    userStore.value.locationData.location.lat,
    userStore.value.locationData.location.lng,
  );
  console.log('sunrise', sunrise);
  qweather = result.data;
  console.log('result', qweather);
  qweather.sunrise = formatTime2(sunrise);
  qweather.sunset = formatTime2(sunset);

  qweather.temperature = qweather.real.weather.temperature;
  qweather.feelst = qweather.real.weather.feelst;
  qweather.info = qweather.real.weather.info;

  qweather.direct = qweather.real.wind.direct;
  qweather.speed = qweather.real.wind.speed;
  qweather.power = qweather.real.wind.power;
  qweather.rain = qweather.real.weather.rain;
  qweather.humidity = qweather.real.weather.humidity;
  qweather.predict = qweather.predict;
  today.setHours(0, 0, 0, 0);

  weatherStore.setResult(qweather);
  const filteredData2 = qweather.tempchart.filter((item) => {
    // Parse timestamp
    const timestamp = new Date(item.time);
    timestamp.setHours(0, 0, 0, 0); // Set to midnight

    // Compare dates, keep only data from today
    return timestamp.getTime() === today.getTime();
  });
  qweather.wl = qweather.tempchart;
  qweather.today = filteredData2[0];
  // console.log('qweather', qweather)
  const result2 = await proxy.$ax.get(
    `/geoapi-qweather/city/lookup?location=${userStore.value.locationData.address_component.city.replace(
      '市',
      '',
    )}&key=12ac1c97d8054a058e096d59efe6182e`,
  );
  // console.log('result2', result2)
  const result3 = await proxy.$ax.get(
    `/devapi-qweather/indices/1d?type=0&location=${result2.location[0].id}&key=12ac1c97d8054a058e096d59efe6182e`,
  );

  zs = result3.daily;
  console.log('zs', zs);
  isLoading.value = false;
}
loadData();
const now = new Date();
// 计算下一个小时的第一分钟的时间
const nextHour = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 1, 0);
// 计算当前时间到下一个小时第一分钟的时间差
const duay = nextHour.getTime() - now.getTime();
// 设置定时器，在时间差过去后调用loadData方法
let timer = setTimeout(() => {
  loadData();
  // 每隔一小时调用loadData方法
  setInterval(() => {
    loadData();
  }, 60 * 60 * 1000);
}, duay);
function formatTime2(time) {
  const hours = time.getHours().toString().padStart(2, '0');
  const minutes = time.getMinutes().toString().padStart(2, '0');
  return `${hours}:${minutes}`;
}
function geticon(info) {
  console.log('info', info);
  if (info === '晴') {
    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/clear-day.svg';
  }
  if (info === '多云') {
    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/cloudy.svg';
  }
  if (info === '阴') {
    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/extreme.svg';
  }
  if (info.includes('雪')) {
    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/snow.svg';
  }
  if (info.includes('雨')) {
    return 'https://zt-1304966785.cos.ap-nanjing.myqcloud.com/rain.svg';
  }
  if (info === '9999') {
    return 'https://ztapp-1304966785.cos.ap-nanjing.myqcloud.com/svg/code-green.svg';
  }
}
provide('geticon', geticon);

onBeforeUnmount(() => {
  // 在组件实例卸载前执行一些清理工作
  clearInterval(this.timer);
  timer = null;
});
</script>

<style scoped lang="less"></style>
